<template lang="">
  <div class="system-role">
    <el-row :gutter="20">
      <el-col :span="16">
        <el-card>
          <p class="tips">双击选择一个角色,进行权限修改.</p>

          <search-list
            ref="roleList"
            :pagination="pagination"
            :api-url="$url.SysRoleList"
            :option="searchOpt"
            :itemPerRow="8"
            highlight-current-row
            @current-change="clickRow"
          >
            <el-table-column prop="id" label="ID" width="50"></el-table-column>
            <el-table-column prop="name" label="角色名称" width="120"></el-table-column>
            <el-table-column prop="level" label="角色等级" width="80"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="150px"></el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template slot-scope="scope">
                <el-button type="text" @click="check(scope.row)" v-permission="['role:check']">
                  修改
                </el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="del(scope.row)"
                  v-permission="['role:del']"
                ></el-button>
              </template>
            </el-table-column>

            <div class="btn-after" slot="btn-after">
              <el-button
                type="success"
                v-permission="['role:add']"
                icon="el-icon-plus"
                @click="dialogShow = true"
              >
                新增角色
              </el-button>
            </div>
          </search-list>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card>
          <div slot="header" class="card-title">
            <div>
              <p style="font-size: 12px;color: #888">角色权限修改</p>
              <p style="font-weight: bolder">{{ currentRole.name }}</p>
            </div>
            <span class="card-title-rbtn">
              <router-link v-permission="['menu']" :to="{ name: 'SystemMenu' }">
                <el-button>编辑权限菜单</el-button>
              </router-link>
              <el-button
                icon="el-icon-check"
                type="primary"
                @click="saveRolePermission"
                style="margin-left: 5px"
                v-permission="['role:permission']"
                v-if="currentRole.id"
                v-loading="loading"
              >
                保存
              </el-button>
            </span>
          </div>
          <el-tree
            v-if="currentRole.id"
            :props="{ label: 'title', children: 'children' }"
            :data="menuData"
            :disabled="!currentRole.id"
            ref="permissionTree"
            node-key="id"
            default-expand-all
            show-checkbox
            check-strictly
          ></el-tree>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      :title="dialogInfo.id ? `修改角色` : `新增角色`"
      :visible="dialogShow"
      :show-close="false"
      width="500px"
    >
      <el-form
        label-position="top"
        :rules="roleRule"
        :model="dialogInfo"
        ref="roleFormDialog"
        @submit.native.prevent
      >
        <el-form-item prop="name" label="角色名称">
          <el-input v-model.trim="dialogInfo.name"></el-input>
        </el-form-item>
        <el-form-item prop="level" label="角色级别(数值越小，级别越大)">
          <el-input-number :min="1" :max="999" v-model.trim="dialogInfo.level"></el-input-number>
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input
            type="textarea"
            resize="none"
            show-word-limit
            maxlength="100"
            v-model.trim="dialogInfo.description"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="closeDialog">关 闭</el-button>
        <el-button
          type="success"
          @click="saveRole"
          v-loading="loading"
          icon="el-icon-check"
          v-permission="['role:check']"
        >
          保 存
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { FormRuleConf } from '@/config';
  import { cloneDeep } from 'lodash';

  export default {
    data() {
      return {
        searchOpt: [],
        menuData: [{ children: [] }],
        currentRole: {},

        loading: false,
        dialogShow: false,
        dialogInfo: {},
        pagination: {
          size: 1000,
        },
        ...FormRuleConf.Role,
      };
    },
    mounted() {
      this.$service.SysMenuList().then((res) => {
        this.menuData = res;
      });
    },
    methods: {
      clickRow(row) {
        this.currentRole = cloneDeep(row);
        const menus = row.menus || [];
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedNodes(
            menus.map((menu) => {
              return {
                id: menu.id,
                label: menu.title,
              };
            }),
          );
        });
      },
      /**
       * 保存角色
       */
      saveRole() {
        this.$refs['roleFormDialog'].validate((valid) => {
          if (valid && !this.loading) {
            this.loading = true;

            this.$service
              .SysRoleSave(this.dialogInfo, {
                ...JSON_HEADER,
              })
              .then((res) => {
                this.$message.success('角色信息保存成');
                this.closeDialog();
                this.$refs['roleList'].getList();
              })
              .finally(() => {
                this.loading = false;
              });
          }
        });
      },
      /**
       * 删除role
       */
      del(row) {
        if (this.loading) return;

        this.$confirm(`确认删除 ${row.name} 吗?`, '删除')
          .then(() => {
            this.loading = true;
            return this.$service.SysRoleDel({
              id: row.id,
            });
          })
          .then(() => {
            this.$message.success('删除角色成功');
            this.$refs.roleList.getList();
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /**
       * 修改现有的数据
       */
      check(row) {
        this.dialogShow = true;
        this.dialogInfo = cloneDeep(row);
      },
      /**
       * 关闭弹窗
       */
      closeDialog() {
        this.dialogShow = false;
        this.dialogInfo = {};
      },
      /**
       * Tree check
       */
      saveRolePermission() {
        if (this.loading) return;
        this.loading = true;

        const nodes = this.$refs.permissionTree.getCheckedNodes();
        this.$service
          .SysRoleSave(
            {
              ...this.currentRole,
              menus: nodes.map((node) => {
                return {
                  id: node.id,
                };
              }),
            },
            {
              ...JSON_HEADER,
            },
          )
          .then((res) => {
            this.$message.success('保存角色权限成功');
            this.$refs.roleList.getList();
          })
          .finally(() => {
            this.loading = false;
          });
      },
    },
  };
</script>

<style lang="less" scoped>
  .system-role {
    /deep/ .el-table__row {
      cursor: pointer;
    }
  }
</style>
